/*
 * @Descripttion: 
 * @version: 
 * @Author: 周志伟
 * @Date: 2021-04-16 17:09:48
 * @LastEditors: 周志伟
 * @LastEditTime: 2021-05-31 15:39:56
 */
'use strict';
const Fs = require('fs');
const Path = require('path');
module.exports = {
  load() {
    // execute when package loaded
  },

  unload() {
    // execute when package unloaded
  },

  // register your ipc messages here
  messages: {
    'open'() {
      // open entry panel registered in package.json
      Editor.Panel.open('zzw_Preview');
    },
    'say-hello'() {
      Editor.log('Hello World!');
      // send ipc message to panel
      Editor.Ipc.sendToPanel('zzw_Preview', 'zzw_Preview:hello');
    },
    'clicked'() {
      Editor.log('Button clicked!');
      // 遍历资源目录下的文件
      const assetsPath = Editor.url('db://assets/');
      const documentArr = this.map(assetsPath);
      let str = "bundleList=";
      for (let i = 0; i < documentArr.length; i++) {
        if (documentArr[i] != "scenes" && documentArr[i] != "resources" && documentArr[i] != "script" && documentArr[i] != "common"&& documentArr[i] != "effect") {

          if (i === documentArr.length - 1) {
            str = str + documentArr[i] + "@sp_q"
          } else {
            str = str + documentArr[i] + "@sp_q,"
          }
        }
        // if (['scene', 'prefab', 'rescources', 'res', 'script'].includes(documentArr[i])) {

        // }
      }
      let str1 = null;
      if (str === "bundleList=") {
        str1 = "http://localhost:7456/?userRole=1&roomId=2"
      } else {
         str1 = "http://localhost:7456/?userRole=1&" + str + "&roomId=2"
      }
      Editor.log('预览地址:');
      Editor.log(str1);


      
    }
  },
  /**
    * 遍历文件/文件夹并执行函数
    * @param {Fs.PathLike} path 路径
    * @param {(filePath: Fs.PathLike, stat: Fs.Stats) => void} handler 处理函数
    */
  map(path) {
    if (!Fs.existsSync(path)) return
    const names = Fs.readdirSync(path);
    const documentArr = [];
    for (const name of names) {
      let _path = Path.join(path, name)
      if (Fs.existsSync(_path)) {
        const stats1 = Fs.lstatSync(_path);
        if (stats1.isDirectory()) {
          const name1 = name.replace(/\s+/g, "");

          documentArr.push(name1)
        }
      }
    }
    return documentArr;
  }
};